package org.itzheng.myrxframe;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;

import org.itzheng.and.activity.permissions.IPermissionManager;
import org.itzheng.and.baseutils.json.JsonHelper;
import org.itzheng.and.baseutils.log.LogHelper;
import org.itzheng.myrxframe.base.BaseActivity;
import org.itzheng.myrxframe.http.callback.IBindDataCallBack;
import org.itzheng.myrxframe.http.network.NetDataTest;
import org.itzheng.myrxframe.http.retrofit.utils.ApiServiceUtils;
import org.itzheng.myrxframe.http.rxjava.RxHelper;
import org.itzheng.myrxframe.realize.adpter.rcv.MainMenuAdapter;
import org.itzheng.myrxframe.realize.binddata.DataMain;
import org.itzheng.myrxframe.upt.UtpApiService;
import org.itzheng.myrxframe.upt.VersionInfo;
import org.itzheng.myrxframe.upt.VersionUpt;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class MainActivity extends BaseActivity {
    private static final String URL_CHECK_VERSION = "http://192.168.4.70:8080/MySevlet/Update/Update.txt";
    private static final int CHOOSE_PHOTO = 109;
    @BindView(R.id.rcvMain)
    RecyclerView rcvMain;
    @BindView(R.id.tvProgress)
    TextView tvProgress;
    @BindView(R.id.pbProgress)
    ProgressBar pbProgress;
    public static boolean isRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isRunning = true;
        SplashActivity.startActivity(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showToast("onCreate");
        ButterKnife.bind(this);
        setMainAdapter();
        App.getInstance().addAppStatusChangeListener(new App.OnAppStatusChangeListener() {
            @Override
            public void onForeground() {
                LogHelper.w(TAG, "onForeground");
            }

            @Override
            public void onBackground() {
                LogHelper.w(TAG, "onBackground");
            }
        });
//        tvProgress = findViewById(R.id.tvProgress);
//        pbProgress = findViewById(R.id.pbProgress);
//        pbProgress.setMax(100);
//        findViewById(R.id.btnVersion).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                checkUpload();
//                pickImage();
////                checkVersion();
//            }
//

//        });
//        findViewById(R.id.btnPermissions).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                requestPermissions(new IPermissionManager.OnRequestPermissionListener() {
//                    @Override
//                    public void grantPermissions(boolean isAllGrant, String[] permissions) {
//                        Log.w(TAG, "grantPermissions: 是否全部允许" + isAllGrant);
//                        showToast("是否全部允许" + isAllGrant);
////                        Toast.makeText(getApplicationContext(), "是否全部允许" + isAllGrant, Toast.LENGTH_LONG).show();
//                    }
//
//                    @Override
//                    public void denyPermissions(boolean isAllDeny, String[] permissions) {
//                        Log.w(TAG, "denyPermissions: 是否全部拒绝" + isAllDeny);
//                        showToast("是否全部拒绝" + isAllDeny);
//                    }
//                }, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE);
//            }
//        });
//        testApi();
    }

    private void pickImage() {
//                Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
//                openAlbumIntent.setType("image/*");
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
    }

    private void setMainAdapter() {
        rcvMain.setLayoutManager(new GridLayoutManager(this, 3));
        rcvMain.setAdapter(new MainMenuAdapter(DataMain.getMenus()));
    }

    @Override
    protected void onDestroy() {
        isRunning = false;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SplashActivity.isSplashEnd(requestCode, resultCode, data)) {
            LogHelper.w(TAG, "onActivityResult: " + "SplashEnd 结束");
            return;
        }
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == Activity.RESULT_OK) {
                    if (data == null) {

                        return;
                    }
                    Uri selectedImage = data.getData();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = getContentResolver()
                            .query(selectedImage, filePathColumns, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String imagePath = c.getString(columnIndex);
                    c.close();
//                    uploadMulti(imagePath);
                    checkUpload(imagePath);
                }
                break;
        }
    }

    private void uploadMulti(String imagePath) {
        //构建body
//addFormDataPart()第一个参数为表单名字，这是和后台约定好的
        File file = new File(imagePath);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "_1_" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                .addFormDataPart("file", "_2_" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        //注意，file是后台约定的参数，如果是多图，file[]，如果是单张图片，file就行
//        builder.addFormDataPart("file", "_1_" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
//        builder.addFormDataPart("file", "_2_" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        RequestBody requestBody = builder.build();
        ApiServiceUtils.create(UtpApiService.class).uploadImage(new HashMap<>(), requestBody)
                .compose(RxHelper.observableIO2Main())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.w(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onNext(ResponseBody value) {
                        try {
                            Log.w(TAG, "onNext: " + value.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.w(TAG, "onError: " + e.toString());
                    }

                    @Override
                    public void onComplete() {
                        Log.w(TAG, "onComplete: ");
                    }
                });

    }

    private void checkUpload(String str) {
        File file = new File(str);
//        File file = new File(imgPath);
//        Map<String, String> header = new HashMap<String, String>();
//        header.put("Accept", "application/json");
//        header.put("Authorization",access_token);
//        File file =new File(filePath);
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), reqFile);
        ApiServiceUtils.create(UtpApiService.class).uploadImage(new HashMap<>(), body)
                .compose(RxHelper.observableIO2Main())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.w(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onNext(ResponseBody value) {
                        try {
                            Log.w(TAG, "onNext: " + value.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        Log.w(TAG, "onError: " + e.toString());
                    }

                    @Override
                    public void onComplete() {
                        showToast("上传成功");
                        Log.w(TAG, "onComplete: ");
                    }
                });
    }

    private void checkVersion() {

        VersionUpt.newInstance().checkUtpUrl(URL_CHECK_VERSION, new VersionUpt.CheckVersionResult<VersionInfo>() {

            @Override
            public void onSuccess(VersionUpt versionUpt, VersionInfo versionInfo) {
                //
                Log.w(TAG, "onSuccess: " + JsonHelper.toJson(versionInfo));
                requestPermissions(new IPermissionManager.OnRequestPermissionListener() {
                    @Override
                    public void grantPermissions(boolean isAllGrant, String[] permissions) {
                        Log.w(TAG, "grantPermissions: 是否全部允许" + isAllGrant);
                        versionUpt.startDownloadApk(versionInfo.url);
                    }

                    @Override
                    public void denyPermissions(boolean isAllDeny, String[] permissions) {
                        Log.w(TAG, "denyPermissions: 是否全部拒绝" + isAllDeny);
                        showToast("是否全部拒绝" + isAllDeny);
                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

            }

            @Override
            public void onError(String error) {
                Log.w(TAG, "onError: " + error);
            }
        }, VersionInfo.class)
                .setDownloadCallback(new VersionUpt.IDownloadCallback() {
                    @Override
                    public void onStart() {
                        LogHelper.w(TAG, Thread.currentThread() + "onStart");
                        tvProgress.setText("onStart");
                    }

                    @Override
                    public void onProgress(long progress, long total) {
                        LogHelper.w(TAG, Thread.currentThread() + "onProgress " + progress + "/" + total);
                        tvProgress.setText(progress + "/" + total);
                        int tProgress = (int) (progress * 100 / total);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            pbProgress.setProgress(tProgress, true);
                        } else {
                            pbProgress.setProgress(tProgress);
                        }
                    }

                    @Override
                    public void onSuccess(String file) {
                        LogHelper.w(TAG, Thread.currentThread() + "onSuccess " + file);
                        VersionUpt.installApk(getApplicationContext(), file);
                    }

                    @Override
                    public void onError(String error, Exception e) {
                        LogHelper.w(TAG, Thread.currentThread() + "onError " + error);
                    }
                });

    }

    private static final String TAG = "MainActivity";

    private void testApi() {
        int page = 1;
        int size = 10;
        IBindDataCallBack iBindDataCallBack = new IBindDataCallBack() {
            @Override
            public void onSuccess(List items) {
                Log.w(TAG, Thread.currentThread().getName() + " onSuccess: " + JsonHelper.toJson(items));
            }

            @Override
            public void onError(String error) {
                Log.w(TAG, Thread.currentThread().getName() + " onError: " + error);
            }
        };
        NetDataTest.newInstance(this).getShareList3(page, size, iBindDataCallBack);
    }

    @OnClick(R.id.btnUpload)
    public void onViewClicked() {
        Beta.checkUpgrade();
        requestPermissions(new IPermissionManager.OnRequestPermissionListener() {
            @Override
            public void grantPermissions(boolean isAllGrant, String[] permissions) {
//                pickImage();
            }

            @Override
            public void denyPermissions(boolean isAllDeny, String[] permissions) {

            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);

    }
}
